<?php

/*
 A comment order value must be passed to the wakka class LoadComments method
 else it may fail to return the comment array.
 */
define('DEFAULT_COMMENT_ORDER', NULL);
#define('DEFAULT_COMMENT_ORDER', COMMENT_ORDER_DATE_ASC);

function show_page_comments($tag, $user_wants)
{
    if ( !isset($_SESSION['show_comments'][$tag]) ) {
        $_SESSION['show_comments'][$tag] = ($user_wants ? 1 : NULL);
    }

    if (isset($_GET['show_comments'])) #312
    {
        switch($_GET['show_comments']) #312
        {
            case "0":
                $_SESSION['show_comments'][$tag] = NULL;
                break;
            case "1":
                $_SESSION['show_comments'][$tag] = 1;
                break;
        }
    }

    return $_SESSION['show_comments'][$tag];
}

function build_comment_form($wikka)
{
    $form_t = <<<XHTML

<div id="commentform">

    <!-- FormOpen --> %s
    <label for="commentbox">Add a comment to this page:<br />
        <textarea id="commentbox" name="body" rows="6" cols="78"></textarea><br />
        <input type="submit" value="Add Comment" accesskey="s" />
    </label>
    <!-- CloseOpen --> %s
</div>

XHTML;

    return sprintf( $form_t,
                    $wikka->FormOpen('addcomment'),
                    $wikka->FormClose() );
}

function build_recaptcha_comment_form($wikka)
{
    require_once('3rdparty/plugins/recaptcha/recaptchalib.php');
    $is_logged_in = ( $wikka->GetUser() ) ? 1 : 0;

    $form_t = <<<XHTML

<div id="commentform">

    <!-- javascript warning -->%s

    <!-- FormOpen --> %s
    <label for="commentbox">Add a comment to this page:<br />
        <textarea id="commentbox" name="body" rows="6" cols="78"></textarea><br />
        <!-- <input type="submit" value="Add Comment" accesskey="s" /> -->

        <!-- recaptcha -->
        <div id="comment_recaptcha" style="display:none;">
            %s
        </div>

        <!-- button -->%s
    </label>
    <!-- CloseOpen --> %s

    <script>
        var rc_user_is_logged_in = %s;
        var rc_recaptcha_fail = %s;
        var rc_preset_body = "%s";

        if ( rc_recaptcha_fail ) {
            var comment_text = rc_preset_body.replace(/~~~/g,'\\n');
            \$('#commentbox').val(comment_text);
            \$('#comment_submit').val('Submit Comment');
            rc_show_captcha();
        }

        function rc_comment_presubmit() {
            var is_recaptcha_submit = \$('#comment_submit').val() == 'Submit Comment';

            if ( ! rc_comment_form_is_valid() ) {
                if ( ! $('#rc_warning').length > 0 ) {
                    var em = '<em id="rc_warning" class="error">/em>';
                    \$(em).insertBefore('#commentbox');
                }
                \$('#rc_warning').text('please input your comment below');
                \$("#commentbox").focus();
            }

            else if ( rc_user_is_logged_in ) {
                rc_submit_comment(1);
            }

            else if ( is_recaptcha_submit ) {
                rc_submit_comment(0);
            }

            else {
                rc_show_captcha();
                \$('#comment_submit').val('Submit Comment');
            }
        }

        function rc_comment_form_is_valid() {
            //console.log('comment', \$('#commentbox').val());
            return \$('#commentbox').val().length > 0;
        }

        function rc_show_captcha() {
            \$('#comment_recaptcha').show();
            \$("#recaptcha_response_field").focus();
        }

        function rc_submit_comment(is_logged_in) {
            if ( is_logged_in ) {
                rc_autosubmit_comment_form();
            }
            else {
                rc_autosubmit_comment_form();
            }
        }

        function rc_autosubmit_comment_form() {
            var \$form = \$('#commentform').find('form:first');
            \$form.submit();
        }

        function rc_autosubmit_recaptcha() {
            var \$form = \$('#commentform').find('form:first');
            \$form.attr('action', 'http://klenwell/is/CommentSandbox');
            \$form.submit();
        }

    </script>
</div>

XHTML;

    $recaptcha_error = ( isset($_SESSION['recaptcha_comment_error']) )
        ? $_SESSION['recaptcha_comment_error']
        : null;
    $preset_body = ( isset($_SESSION['recaptcha_comment_body']) )
        ? escape_returned_body($_SESSION['recaptcha_comment_body'])
        : '';

    $recaptcha_html = recaptcha_get_html( $wikka->GetConfigValue('rc_public_key'),
                                          $recaptcha_error );

    $noscript = '';
    if ( ! $is_logged_in ) {
        $noscript = <<<XHTML
    <noscript>
        <h5 class="warning">
            To control spam, javascript must be enabled to submit a comment.
        </h5>
    </noscript>
XHTML;
    }

    if ( $is_logged_in ) {
        $submit_bx = <<<XHTML
        <input type="submit" id="comment_submit" value="Submit Comment" accesskey="s" />
XHTML;

    }
    else {
        $submit_bx = <<<XHTML
        <input type="button" id="comment_submit" value="Add Comment" accesskey="s"
            onclick="rc_comment_presubmit()" />
XHTML;
    }

    return sprintf( $form_t,
                    $noscript,
                    $wikka->FormOpen('addcomment'),
                    $recaptcha_html,
                    $submit_bx,
                    $wikka->FormClose(),
                    $is_logged_in,
                    (int) !empty($recaptcha_error),
                    $preset_body );
}

function escape_returned_body($body)
{
    return (string)str_replace(array("\r\n", "\r", "\n"), '~~~', $body);
}


function build_collapsed_comment_block($wikka)
{
    $comment_f = <<<XHTML
<div id="comments">
    <div id="commentheader">
        <!-- comment session flash message --> %s
        %s <br />
        [<a href="%s">%s</a>]
    </div>
</div>
XHTML;

    $comments = $wikka->LoadComments($wikka->tag, DEFAULT_COMMENT_ORDER);

    # comment flash message
    $comment_flash = get_comment_flash();

    switch ( count($comments) )
    {
        case 0:
            $comment_label = 'There are no comments on this page. ';
            if ( $wikka->HasAccess('comment_post') ) {
                $showcomments_text = 'Add comment';
            }
            else {
                $comment_label = '';
                $showcomments_text = 'There are no comments on this page';
            }
            break;
        case 1:
            $comment_label = 'There is one comment on this page. ';
            $showcomments_text = 'Display comment';
            break;
        default:
            $comment_label = sprintf('There are %s comments on this page. ',
                                     count($comments));
            $showcomments_text = 'Display comments';
            break;
    }

    return sprintf( $comment_f,
                    $comment_flash,
                    $comment_label,
                    $wikka->Href('', '', 'show_comments=1#comments'),
                    $showcomments_text );
}


function build_comment_block($wikka)
{
    $comments_f = <<<XHTML
<div id="comments">

    <!-- header -->
    %s

    <!-- form -->
    %s

    <!-- list -->
    <div id="commentlist">
    %s
    </div>

</div>
XHTML;

    $comment_header_f = <<<XHTML
<div id="commentheader">
    <!-- comment session flash message --> %s
    Comments [<a href="%s">Hide comments/form</a>]
</div>
XHTML;

    $comment_list_f = <<<XHTML
<div id="commentlist">
    <!-- comment items -->
%s
</div>
XHTML;

    $comment_item_f = <<<XHTML
<div class="comment">
    <span id="comment_%s"></span>
        <!-- comment --> %s
    <div class="commentinfo">
        &mdash; %s (%s)
        %s
    </div>
</div>
XHTML;

    $comment_del_f = <<<XHTML
    <!-- FormOpen --> %s
        <input type="hidden" name="comment_id" value="%s" />
        <input type="submit" value="Delete Comment" />
    <!-- FormClose --> %s
XHTML;

    $comment_header = '';
    $comment_list = '';
    $comment_form = '';
    $CommentItemList = array();
    $current_user = $wikka->GetUserName();

    $comment_header = sprintf($comment_header_f,
                              get_comment_flash(),
                              $wikka->Href('', '', 'show_comments=0'));

    $comments = $wikka->LoadComments($wikka->tag, DEFAULT_COMMENT_ORDER);

    if ( $comments )
    {
        foreach ( $comments as $comment )
        {
            $comment_user = ( $wikka->LoadUser($comment['user']) )
                ? $wikka->Format($comment['user'])
                : $comment['user'];

            $show_delete = $wikka->UserIsOwner() ||
                $current_user == $comment['user'] ||
                ( $wikka->config['anony_delete_own_comments'] &&
                  $current_user == $comment['user'] );

            if ( $show_delete ) {
                $comment_delete_form = sprintf( $comment_del_f,
                    $wikka->FormOpen("delcomment"),
                    $comment['id'],
                    $wikka->FormClose() );
            }
            else {
                $comment_delete_form = '';
            }

            $CommentItemList[] = sprintf($comment_item_f,
                $comment['id'],
                $comment['comment'],
                $comment_user,
                $comment['time'],
                $comment_delete_form
            );
        }

        $comment_list = implode("\n", $CommentItemList);
    }
    else {
        $comment_list = '<div class="nocomments">There are no comments.</div>';
    }

    # comment form
    if ( $wikka->HasAccess('comment_post') )
    {
        if ( $wikka->GetConfigValue('use_recaptcha') ) {
            $comment_form = build_recaptcha_comment_form($wikka);
        }
        else {
            $comment_form = build_comment_form($wikka);
        }
    }

    return sprintf( $comments_f,
                    $comment_header,
                    $comment_form,
                    $comment_list );
}

/**
 * add comment flash message to session
 * session variable is a list of tuples (message, type)
 */
function add_comment_flash($message, $type='neutral')
{
    if ( !isset($_SESSION['comment_flash']) ) {
        $_SESSION['comment_flash'] = array();
    }
    $_SESSION['comment_flash'][] = array($message, $type);
}

function get_comment_flash()
{
    $comment_flash = '';
    if ( isset($_SESSION['comment_flash']) ) {
        $FlashList = array();
        foreach ( $_SESSION['comment_flash'] as $tuple ) {
            $message = $tuple[0];
            $class = $tuple[1];
            $FlashList[] = sprintf('<div class="comment_flash %s">%s</div>',
                                   $class, $message);
        }
        $comment_flash = implode("\n", $FlashList);
        unset($_SESSION['comment_flash']);
    }
    return $comment_flash;
}

?>
